﻿package com.push.notifications;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;

import com.google.android.gcm.GCMBaseIntentService;
import com.google.android.gcm.GCMRegistrar;
import com.push.notifications.ServerUtilities;
import com.push.notifications.R;
import com.push.notifications.categoryItem;
import com.push.notifications.UI_ListServiceFirst;
import com.push.notifications.UI_ListServiceFirst.ViewHolder;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class NotificationActivity extends Activity {

	
	 public static final String SMS_SENT = "SMS_SENT";
	 public static final String SMS_DELIVERED = "SMS_DELIVERED";
	 UI_ListServiceFirst adapter;
	 public static List<categoryItem> list = new ArrayList<categoryItem>();
	 
	 AsyncTask<Void, Void, Void> mRegisterTask;
	 
	 static boolean Dialog_ok= false;
	 static boolean Dialog_cancel= false;
	 public static String regId = ""; 
	 static String densityDisplay = null;
	 
	 private boolean isReceiverRegistered = false;
	 public static Handler han_notification;
	 
	 public boolean hasNotDialog = true;	
	 
	 private String path;
	 private String urlPath;
	 private String message;
	 
	 
	 public class CrashExceptionHandler implements
     java.lang.Thread.UncaughtExceptionHandler {
	 private final Context mContext;
     private final Class<?> activityClass;

	 public CrashExceptionHandler(Context context, Class<?> c) {
	
	     mContext = context;
	     activityClass = c;
	 }
	
	 public void uncaughtException(Thread thread, Throwable exception) {
	
	     Intent intent = new Intent(mContext, activityClass);	    
	     //you can use this String to know what caused the exception and in which Activity	    	     
	     mContext.startActivity(intent);
	     //for restarting the Activity	
	     Log.e("Crash report", "Application is crash");
	     System.exit(0);
	 }
	}
		 
	 
	 private Thread.UncaughtExceptionHandler onRuntimeError= new Thread.UncaughtExceptionHandler() {
	        public void uncaughtException(Thread thread, Throwable ex) {
	        	 finish();
	        	Intent i = getBaseContext().getPackageManager()
	                    .getLaunchIntentForPackage( getBaseContext().getPackageName() );
	       i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	       startActivity(i);
	        }
	    };
	  
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);               
        Thread.setDefaultUncaughtExceptionHandler(new CrashExceptionHandler(this,NotificationActivity.class));
        setContentView(R.layout.activity_notification); 
        
        
        TextView textTitlte= (TextView) findViewById(R.id.textView10);
   	 	textTitlte.setText(Definitions.TITLE_MAIN);
   	 	setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);


        han_notification = new Handler() {

            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                switch(msg.what) {

                case 0:
                    finish();
                    break;
                case 1:
                	showDialog(Definitions.DIALOG_WARNING);
                	WebServicesTask.bNotReponse = false;
                	hasNotDialog= false;
                	break;
                case 2:
                	startService();
                	updateListView(true);                
                	break;
                case 3:
                	updateVersionDialog();
                	break;
                case 4:
                	updateSubNews();
                	break;
                }
            }

        };   
        Display display = getWindowManager().getDefaultDisplay();
        int width = display.getWidth();
        int height = display.getHeight();
        //
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        float a = ( dm.density * 80 - 10 );
        String aSt = Integer.toString( (int) a);
        densityDisplay = "&w="+ aSt + "&h="+aSt;
        if(!CUtilsFunction.checkConnect(this))
		 {
        	//list = database.getAllCategoryByParentId(-1); //get all category with parent id = -1
        	//list = databaseWrapper.getListCategoryById(this,-1);
        	//updateListView(false);
        	showDialog(Definitions.DIALOG_INTERNET);
		 }
		 else //Online
		 {
			 //create a new thread to get data
			 
			 getData();
			 			
				Thread getdataThread = new Thread() {					
					@Override
					public void run() {
						try {
							
							while ( WebServicesTask.sData == "" ) {
								
								sleep(100);				
								if(hasNotDialog && WebServicesTask.bNotReponse == true)
								{		
									han_notification.sendEmptyMessage(Definitions.DIALOG_WARNING);
									 
								}
								
							}
						} catch (InterruptedException e) {
							// do nothing
						} finally {
							
							han_notification.sendEmptyMessage(2);
						}
					}
				};
				getdataThread.start();
	
			 //end thread
			 
		 }
               
    }
    
    private void startService() {
		Intent intent = new Intent(this, GetDataService.class);
		startService(intent);
		GetDataThread
				.setonGetDataCompleteListener(new OnUploadingCompleteListener() {

					@Override
					public void OnGetDataComplete(Context context,
							String response) {
						// TODO Auto-generated method stub
						try {							
							if (!urlPath.equalsIgnoreCase("null")) {
								han_notification.sendEmptyMessage(3);
							}
						} catch (Exception e) {
							// TODO: handle exception
						}

					}
				});
	}
    
    private void updateVersionDialog() {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setMessage(message);
		alert.setPositiveButton(getString(R.string.text_ok),

		new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				dialog.cancel();
				updateNewVersion();
			}
		});
		alert.setNegativeButton(getString(R.string.text_no),
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.cancel();
					}
				});
		alert.show();
	}
    
    

	private void updateNewVersion() {
		boolean available = false;
		Intent intent = new Intent(this, DownloadService.class);
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			path = Environment.getExternalStorageDirectory().getAbsolutePath()
					+ "/PushNotification/install/" + this.getString(R.string.app_name)
					+ ".apk";
			available = true;
		} else {
			File internalCacheDir = this.getCacheDir();
			// apparently on some configurations this can come back as null
			if (internalCacheDir == null) {
				available = false;
			} else {
				path = internalCacheDir.getAbsolutePath() + "/PushNotification/install/"
						+ this.getString(R.string.app_name) + ".apk";

				available = true;
			}

		}
		if (available) {
			Bundle sendBundle = new Bundle();
			sendBundle.putString("url", urlPath);
			sendBundle.putString("fileName", this.getString(R.string.app_name)
					+ ".apk");
			sendBundle.putString("name", this.getString(R.string.app_name)
					+ ".apk");
			intent.putExtras(sendBundle);
			ServiceQueueDownloadUtil
					.setOnDownloadStartListener(new OnDownloadStartListener() {
						@Override
						public void onDownloadStart(final IDownloadedItem item) {
							// TODO Auto-generated method stub
							Thread t = new Thread(new Runnable() {
								@Override
								public void run() {
									// TODO Auto-generated method stub
									ServiceQueueDownloadUtil
											.requestDumpGet(urlPath);
								}
							});
							t.start();
						}
					});
			ServiceQueueDownloadUtil
					.setOnDownloadCompleteListener(new OnDownloadCompleteListener() {
						@Override
						public void onDownloadComplete(final Context context,
								final IDownloadedItem item) {
							// TODO Auto-generated method stub
							File apkFile = new File(path);
							Intent i2 = new Intent();
							i2.setAction(android.content.Intent.ACTION_VIEW);
							i2.setDataAndType(Uri.fromFile(apkFile),
									"application/vnd.android.package-archive");
							startActivity(i2);
						}
					});
			startService(intent);
		} else {
			Toast.makeText(getParent(), "Lỗi,vui lòng kiểm tra lại bộ nhớ!", 0)
					.show();
		}

	}

protected void sendSMS(String phoneNumber, String message) {
		
		PendingIntent piSend = PendingIntent.getBroadcast(this, 0, new Intent(
				SMS_SENT), 0);
		PendingIntent piDelivered = PendingIntent.getBroadcast(this, 0,
				new Intent(SMS_DELIVERED), 0);
		SmsManager manager = SmsManager.getDefault();
		try {
			manager.sendTextMessage(phoneNumber, null, message, piSend,
					piDelivered);
			
		} catch (Exception e) {
			// TODO: handle exception
			
		}

	}
	
    public void updateDataToDatabase()
    {
    	list.clear();
        list = getListCategory();
        //Compare with in database
        for(int k =0 ; k < list.size(); k++)
		 {
			 categoryItem itemTemp = list.get(k);					 
			 categoryItem itemDb = databaseWrapper.getCategory(this,itemTemp.getCategory(),itemTemp.getParentId());
			 if(itemDb != null)
			 {
				 itemTemp.setSelected(itemDb.isSelected());
				 list.set(k, itemTemp);
			 }
			
		 }
        	
         //Empty category data base
        	databaseWrapper.deleteAllCategoryHaveParentId(this,-1);// at root
         //Update to database
		 for(int j =0 ; j < list.size(); j++)
		 {
			 categoryItem itemTemp = list.get(j);			
			 databaseWrapper.insertCategory(this,itemTemp);
			
		 }
		 
		 startService();
		 
		 
		 
    }
    
    private String getImei() {
		TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
		if(telephonyManager != null)
			return telephonyManager.getDeviceId();
		
		return null;
	}
	private String getVersionName() {
		try {
			return this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName;
		} catch (Exception e) {
			return "1.0";
		}
	}
	
    public void updateListView(boolean bOnline)
    {        	
    	if(bOnline == true)
    		updateDataToDatabase();
   	 	ListView listView = (ListView) findViewById(R.id.my_list);   	  
    	adapter = new UI_ListServiceFirst(this,NotificationActivity.list);
        listView.setAdapter(adapter);  
        if(bOnline == true)
        	onRegisterGcm();
        adapter.notifyDataSetChanged();
   
    }

    public  void getData()
 	 {    
    	WebServicesTask.bNotReponse = false;
    	WebServicesTask.sData = "";	
    	String urlRequest = Definitions.SERVICE_URL; 
    	WebServicesTask wst = new WebServicesTask(WebServicesTask.GET_TASK, this, Definitions.TITLE_LOADING);
    	wst.setLoading(true);
    	wst.execute(new String[] {urlRequest});
 	 }
     
    
	 public  List<categoryItem> getListCategory()
	 {    		
		 List<categoryItem> listNew = new ArrayList<categoryItem>();
		 
		 try {
				JSONArray jsonArray = new JSONArray(WebServicesTask.sData);								
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject jsonObject = jsonArray.getJSONObject(i);

					String sId = jsonObject.getString("extendId");
					int nId = Integer.parseInt(sId);
					String sName = jsonObject.getString("extendName");
					String sIdIcon = jsonObject.getString("extendIcon");
					String sUrlImage = Definitions.LINK_TEST_DOWNLOAD + sIdIcon + densityDisplay;
					String sCommand = jsonObject.getString("extendCommand");
					String sDate = jsonObject.getString("lastUpdate");
					String sDesc = jsonObject.getString("extendDesc");
					//String name,String img, boolean status_chek, int nCategory,int nIdParent,
					//int nPos,String command, String sDate , String sDesc
					listNew.add(new categoryItem(sName,sUrlImage,true,nId,-1,i,sCommand,sDate,sDesc));
				}					
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 	
		return listNew;
	 }
	 	

    public void oncheckDevice()
    {
        GCMRegistrar.checkDevice(this);
        // Make sure the manifest was properly set - comment out this line
        // while developing the app, then uncomment it when it's ready.
        GCMRegistrar.checkManifest(this);    
    }
    
    public void onRegisterGcm()
    {
    	//ServerUtilities.registerCategory(NotificationActivity.regId,"-1");
    	checkNotNull(Definitions.SERVER_URL, "http://vipmobi.net:8082/gcm-demo");
        checkNotNull(Definitions.SENDER_ID, "425955995842");
        
        oncheckDevice();
        if (!isReceiverRegistered) {
        registerReceiver(mHandleMessageReceiver,new IntentFilter(Definitions.DISPLAY_MESSAGE_ACTION));       
        }
        onRegister();
        
    }
    
    public void onRegister()
    {
        regId = GCMRegistrar.getRegistrationId(this);
        if (regId.equals("")) {
            // Automatically registers application on startup.
            GCMRegistrar.register(this, Definitions.SENDER_ID);
        } else {
            // Device is already registered on GCM, check server.
        	//Check Expired of this id
        	
            if (GCMRegistrar.isRegisteredOnServer(this)) {                
            	isReceiverRegistered = true;
            } else {
                
                final Context context = this;
                mRegisterTask = new AsyncTask<Void, Void, Void>() {

                    @Override
                    protected Void doInBackground(Void... params) {                    	
                        boolean registered =ServerUtilities.register(context, regId,"-1");
                    	//GCMRegistrar.setRegisteredOnServer(context, true);
                        // At this point all attempts to register with the app
                        // server failed, so we need to unregister the device
                        // from GCM - the app will try to register again when
                        // it is restarted. Note that GCM will send an
                        // unregistered callback upon completion, but
                        // GCMIntentService.onUnregistered() will ignore it.
                        if (!registered) {
                            GCMRegistrar.unregister(context);
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                        mRegisterTask = null;
                    }

                };
                mRegisterTask.execute(null, null, null);
            }
        }
    }
      
    
    
    @Override
    protected void onDestroy() {
        if (mRegisterTask != null) {
            mRegisterTask.cancel(true);
        }
        if (isReceiverRegistered) {
            try {
                unregisterReceiver(mHandleMessageReceiver);
                GCMRegistrar.onDestroy(this);
            } catch (IllegalArgumentException e) {
                // TODO: handle exception
            }
            isReceiverRegistered = false;
        }           
        super.onDestroy();
    }
/*
    public void onResume() {
        if (!isReceiverRegistered) {
            registerReceiver(gcmReceiver, gcmFilter);
            isReceiverRegistered = true;
        }
}
*/
    private void checkNotNull(Object reference, String name) {
        if (reference == null) {
            throw new NullPointerException(
                    getString(R.string.error_config, name));
        }
    }

    private final BroadcastReceiver mHandleMessageReceiver =
            new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String newMessage = intent.getExtras().getString(Definitions.EXTRA_MESSAGE);
            //mDisplay.append(newMessage + "\n");
        }
    };
    public  OnClickListener myClickListener = new OnClickListener() {
		public void onClick(View listview_click) {			
				// lay vi tri
				ViewHolder viewHolder_here = null;
				viewHolder_here = (ViewHolder) listview_click.getTag();
				int positon_here = viewHolder_here.post;
				CharSequence T= viewHolder_here.text.getText();
				// chuyen ra 1 Model
				categoryItem mode_selected =list.get(positon_here);
				Log.e("button", "OnClickListener: "+ T + mode_selected.getCategory());
				
		       if(mode_selected.getCommand().equalsIgnoreCase("-1") )
		       {		    			    	   
		    	   	newsTabManager.currentItem =  mode_selected;
		    	   	if(mode_selected.isSelected())//Need to save to database
		    	   	{
		    	   		if( CUtilsFunction.checkConnect(NotificationActivity.this))
		    	   		{
		    	   			getJsonSubNews(mode_selected.getCategory());
			    	   		
			    	   		//Create a thread
			    	   		Thread getSubNewsThread = new Thread() {
			    				
			    				@Override
			    				public void run() {
			    					try {
			    						
			    						while ((WebServicesTask.sData.equalsIgnoreCase(""))) {
			    							sleep(100);			    							
			    							if(WebServicesTask.bNotReponse == true)
			    							{		
			    								han_notification.sendEmptyMessage(Definitions.DIALOG_WARNING);
			    								 
			    							}
			    						  
			    						}
			    					} catch (InterruptedException e) {
			    						// do nothing
			    					} finally {
			    						//end loading
			    						han_notification.sendEmptyMessage(4);
			    					}
			    				}
			    			};
			    			getSubNewsThread.start();
			    	   		//update this item to database
		    	   		}
		    	   		
		    	   	}
		    	   	else
		    	   	{
		    	   		Intent intent_tab_news = new Intent(NotificationActivity.this , newsTabManager.class);
		    	   		startActivity(intent_tab_news);
		    	   	}
		       }
		       else 
		       { 
		    	    int nCtegoryId = mode_selected.getCategory();
		    	    String sLink = databaseWrapper.getLinkInExpressById(NotificationActivity.this, nCtegoryId);
		    	    if(!sLink.equals(""))
		    	    {
		    	    	popupWebview.sCommand = "";
			            popupWebview.titleDialog = mode_selected.getName();
			            popupWebview.descriptonDialg = "";
			            popupWebview.sortContentDialog = "";
			            popupWebview.urlImage = null;
			            popupWebview.sUrl = sLink;// "http://vipmobi.net:8010/push/xoso.htm";			
						Intent intent_history = new Intent(NotificationActivity.this , popupWebview.class);
						Log.e("button", "OnClickListener: --------------------------------");
						startActivity(intent_history);
		    	    }
		    	    
		       }
		
		    }
		}; 
		
		public void updateSubNews()
		{
			
			 try {
					JSONArray jsonArray = new JSONArray(WebServicesTask.sData);								
					for (int i = 0; i < jsonArray.length(); i++) {
						JSONObject jsonObject = jsonArray.getJSONObject(i);

						String sId = jsonObject.getString("extendId");
						int nId = Integer.parseInt(sId);
						String sParentId = jsonObject.getString("parentId");
						int nParentId = Integer.parseInt(sParentId);
						String sName = jsonObject.getString("extendName");
						String sIdIcon = jsonObject.getString("extendIcon");
						String sUrlImage = Definitions.LINK_TEST_DOWNLOAD + sIdIcon + "&w=45&h=45";
						String sCommand = jsonObject.getString("extendCommand");
						String sDate = jsonObject.getString("lastUpdate");
						String sDesc = jsonObject.getString("extendDesc");
						categoryItem item = new categoryItem(sName,sUrlImage,true,nId,nParentId,i,sCommand,sDate,sDesc);
						databaseWrapper.insertCategory(this, item);
					}					
					
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			 
			 categoryItem itemSelect = newsTabManager.currentItem;
			 databaseWrapper.updateCategory(this, itemSelect.getCategory(), itemSelect.getParentId(), 0);
			 itemSelect.setSelected(false);			 
			 list.set(itemSelect.getPos(), itemSelect);
			 Intent intent_tab_news = new Intent(NotificationActivity.this , newsTabManager.class);
 	   		 startActivity(intent_tab_news);
		}
		
		
		public  void getJsonSubNews(int nParentId)
	   	{    	
			WebServicesTask.bNotReponse = false;
	    	WebServicesTask.sData = "";
	       	String urlRequest = Definitions.SUBNEWS_URL + nParentId; 
	       	WebServicesTask wst = new WebServicesTask(WebServicesTask.GET_TASK, this, Definitions.SUB_LOADING);
	       	wst.setLoading(true);
	       	wst.execute(new String[] {urlRequest});
	   	 }
		
		@Override
		  protected Dialog onCreateDialog(int id) {
			Builder builder = new AlertDialog.Builder(this);
		    switch (id) {
		    case Definitions.DIALOG_WARNING:
			     // Create out AlterDialog
			    {
				     builder.setMessage(Definitions.WARNING_INTERNET);
				     builder.setCancelable(true);
				     builder.setPositiveButton((Definitions.TITLE_QUIT),
				    		    new DialogInterface.OnClickListener() {
				         public void onClick(DialogInterface dialog, int whichButton) {
				          finish();
				         }
				        });
				     builder.setNegativeButton(Definitions.TITLE_RETRY,
				    		    new DialogInterface.OnClickListener() {
				         public void onClick(DialogInterface dialog, int whichButton) {				        					        	
				          dialog.cancel();				         
				          getData();
				          hasNotDialog= true;
				         }
				        });
				     AlertDialog dialog = builder.create();
				     dialog.show();
				     break;
			    }
		    case Definitions.DIALOG_ALERT:
			    {
			      // Create out AlterDialog
			    	 categoryItem currentMode = adapter.getJustClick();		        	     
		        	 builder.setMessage(Definitions.CHECK_WARNING);
				     builder.setCancelable(true);
				     builder.setPositiveButton(Definitions.TITLE_OK,null);				    
				     AlertDialog dialogAlert = builder.create();
				     dialogAlert.show();		       
			         adapter.updateStatus(currentMode);
			         break;
			    }
		    case Definitions.DIALOG_INTERNET:
		    {
		    	builder.setMessage(Definitions.CHECK_INTERNET);
		    	 builder.setPositiveButton((Definitions.TITLE_COLSE),
			    		    new DialogInterface.OnClickListener() {
			         public void onClick(DialogInterface dialog, int whichButton) {
			          finish();
			         }
			        });
		    	 
		    	 AlertDialog dialogClose = builder.create();
		    	 dialogClose.show();
		    	break;
		    }
		    }
		    return super.onCreateDialog(id);
		  }

		  
		public void AddRemoveService()
		{
			categoryItem currentMode = adapter.getJustClick();
			
			int nCategory = currentMode.getCategory();
	    	if(currentMode.isSelected())
	    	{
	    		removeService(NotificationActivity.regId,Integer.toString(nCategory));		    		
	    		currentMode.setSelected(false);
	    	}
	    	else
	    	{
	    		
	    		AddServices(NotificationActivity.regId,Integer.toString(nCategory));		    		
	    		currentMode.setSelected(true);	    	
	    	}
	    	int nStatus = 0;
	    	if(currentMode.isSelected())
	    		nStatus = 1;
	    	databaseWrapper.updateCategory(this,currentMode.getCategory(), currentMode.getParentId(),nStatus); 
	    	adapter.updateStatus(currentMode);
			
		  }
		  //Assign category for device
		  public  void AddServices(String sId, String sCategoryId)
		 {    	
	    	String urlRequest = Definitions.ADD_SERVICE ; 
	    	WebServicesTask wst = new WebServicesTask(WebServicesTask.POST_TASK, this, Definitions.ADD_SERVICE_LOADING);
	        wst.setLoading(true);
	        wst.addNameValuePair("regId", sId);
	        wst.addNameValuePair("categoryId", sCategoryId);
	        wst.execute(new String[] {urlRequest});
		 }
		  
		//remove category for device
		  public  void removeService(String sId, String sCategoryId)
		 {    	
	    	String urlRequest = Definitions.REMOVE_SERVICE +  "/" +sId + "/" +sCategoryId; 
	    	WebServicesTask wst = new WebServicesTask(WebServicesTask.DEL_TASK, this, Definitions.REMOVE_SERVICE_LOADING);	
	    	 wst.setLoading(true);
	        wst.execute(new String[] {urlRequest});
		 }		 
		  
		  public void startDialogSubNews(categoryItem itemSelected)
		  {
			  DialogCategory.itemParent = itemSelected;
			  Intent intent_dialog = new Intent(NotificationActivity.this, DialogCategory.class);
		      startActivity(intent_dialog);		   
		  }
		  @Override
		  	public void onWindowFocusChanged(boolean hasFocus) {
			// TODO Auto-generated method stub
			  Log.e("Notification", ": ------onWindowFocusChanged------------ onWindowFocusChanged-"+hasFocus);
			  if (hasFocus)
			  {
				  GCMIntentService.AppInterrupt =false;
			  }
			super.onWindowFocusChanged(hasFocus);
		  	}
			@Override
			protected void 	onUserLeaveHint(){
				Log.e("Notification", "onUserLeaveHint: ------onUserLeaveHint------------ -");
				GCMIntentService.AppInterrupt =true;
				super.onUserLeaveHint();
			}
			@Override
			protected void onStop() {
				Log.e("Notification", ": ------onStop------------ onStop-"+ GCMIntentService.AppInterrupt);
				if(GCMIntentService.AppInterrupt && historyNewsCategory.isDie)
				{
					finish();
				}
				super.onStop();
			}
}
